package com.wingbow.ticket;
import java.util.List;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by zhengzhiqing on 16/7/5.
 */
@Slf4j
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String pojo2Json(Object object) {
        if (object == null) {
            return "";
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            log.error("json转换异常", e);
        }
        return null;
    }

    /**
     * 将 JSON 字符串转为 Java 对象
     * 
     * @param <T>
     * @param json
     * @param type
     * @return
     * @throws Exception
     */
    public static <T> T fromJSON(String json, Class<T> type) {
        try {
            return  objectMapper.readValue(json, type);
        } catch (Exception e) {
            log.error(String.format("json转换异常json:%s", json), e);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> fromJSONToList(String json, Class<T> type) {
        JavaType javaType = getCollectionType(List.class, type);
        try {
            return (List<T>) objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            log.error(String.format("json转换异常json:%s###class:%s", json, type.getTypeName()), e);
        }
        return null;
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?> elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }


}